package com.ruoyi.business.service.impl;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.domain.TSmjGoodList;
import com.ruoyi.business.domain.TSmjMachineList;
import com.ruoyi.business.mapper.TRecipientInfoMapper;
import com.ruoyi.business.mapper.TSmjGoodListMapper;
import com.ruoyi.business.mapper.TSmjMachineListMapper;
import com.ruoyi.business.service.ITSmjMachineListService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 售卖机信息Service业务层处理
 * 
 * @author admin
 * @date 2024-10-24
 */
@Service
public class TSmjMachineListServiceImpl implements ITSmjMachineListService
{
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TSmjMachineListMapper tSmjMachineListMapper;

    @Autowired
    private TSmjGoodListMapper tSmjGoodListMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TRecipientInfoMapper tUserRecipientInfoMapper;

    /**
     * 查询售卖机信息
     * 
     * @param id 售卖机信息ID
     * @return 售卖机信息
     */
    @Override
    public TSmjMachineList selectTSmjMachineListById(Long id)
    {
        return tSmjMachineListMapper.selectTSmjMachineListById(id);
    }

    /**
     * 查询售卖机信息列表
     * 
     * @param tSmjMachineList 售卖机信息
     * @return 售卖机信息
     */
    @Override
    @DataScope(userAlias = "t")
    public List<TSmjMachineList> selectTSmjMachineListList(TSmjMachineList tSmjMachineList)
    {
        return tSmjMachineListMapper.selectTSmjMachineListList(tSmjMachineList);
    }

    @Override
    public List<TSmjMachineList> selectTSmjMachineListListByNoAuth(TSmjMachineList tSmjMachineList) {
        return tSmjMachineListMapper.selectTSmjMachineListListByNoAuth(tSmjMachineList);

    }

    /**
     * 新增售卖机信息
     * 
     * @param tSmjMachineList 售卖机信息
     * @return 结果
     */
    @Override
    public int insertTSmjMachineList(TSmjMachineList tSmjMachineList)
    {
        tSmjMachineList.setCreateTime(DateUtils.getNowDate());
        return tSmjMachineListMapper.insertTSmjMachineList(tSmjMachineList);
    }

    /**
     * 修改售卖机信息
     * 
     * @param tSmjMachineList 售卖机信息
     * @return 结果
     */
    @Override
    public int updateTSmjMachineList(TSmjMachineList tSmjMachineList)
    {
        tSmjMachineList.setUpdateTime(DateUtils.getNowDate());
        return tSmjMachineListMapper.updateTSmjMachineList(tSmjMachineList);
    }

    /**
     * 删除售卖机信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTSmjMachineListByIds(String ids)
    {
        return tSmjMachineListMapper.deleteTSmjMachineListByIds(Convert.toStrArray(ids));
    }

    @Override
    public int deleteTSmjMachineListByUserRecipientId(Long code) {
        return tSmjMachineListMapper.deleteTSmjMachineListByUserRecipientId(code);

    }

    /**
     * 删除售卖机信息信息
     * 
     * @param id 售卖机信息ID
     * @return 结果
     */
    @Override
    public int deleteTSmjMachineListById(Long id)
    {
        return tSmjMachineListMapper.deleteTSmjMachineListById(id);
    }

    @Override
    public AjaxResult anyscGoods(TSmjMachineList tSmjMachineList)
    {
//        long userId = ShiroUtils.getUserId();
        tSmjMachineList = tSmjMachineListMapper.selectTSmjMachineListById(tSmjMachineList.getId());
        TRecipientInfo tUserRecipientInfo = tUserRecipientInfoMapper.selectTRecipientInfoById(tSmjMachineList.getUserRecipientId());
        String accountJson = tUserRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        if (tUserRecipientInfo.getChannel().contains("_smj_sm_h5")) {
            String[] loginUrls = accountObj.getString("loginUrl").split("login.html");

            headerMap.put("Cookie", accountObj.getString("cookie"));
            headerMap.put("User-Agent", "Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");
//        String url = tSmjMachineList.getMachineGoodUrl();
//        logger.info("货品HTMLurl："+url);
//        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","售货机","");
//        logger.info("返回的HTML:"+httpResponse.getDocument().text());
            logger.info("商品总码HTMLurl：" + loginUrls[0] + "qrcode.html?mid=" + tSmjMachineList.getSmMachineId());
            HttpResponse qrcodeRes = HttpUtils.httpFormGet(loginUrls[0] + "qrcode.html?mid=" + tSmjMachineList.getSmMachineId(), headerMap, "", "");
            Document qrcodedocument = qrcodeRes.getDocument();
            Element imgEle = qrcodedocument.getElementsByTag("img").first();
            String imgDownloadUrl = imgEle.attr("src");
            String filePath = RuoYiConfig.getUploadPath();
            logger.info("保存地址：{}", filePath + "/" + tSmjMachineList.getMachineName() + ".png");
            FileUtils.downloadByCommonIO(imgDownloadUrl, filePath, tSmjMachineList.getMachineName() + ".png");
            String spzmhref = decodeQR(filePath + "/" + tSmjMachineList.getMachineName() + ".png");
            HttpResponse spzmhttpResponse = HttpUtils.httpFormGet(spzmhref, headerMap, "", "售货机", "");
            Document szpzDoc = spzmhttpResponse.getDocument();
            Elements szpzEles = szpzDoc.select("li");
            JSONObject spObj = new JSONObject();
            for (int i = 0; i < szpzEles.size(); i++) {
                String goodUrl = szpzEles.get(i).select("a").first().attr("href");
                String hd = szpzEles.get(i).select("a").first().select("span").first().text();
                spObj.put(hd, goodUrl);
            }
            logger.info("商品总信息：" + spObj);
            if(szpzEles.size()==0){
                tSmjGoodListMapper.deleteTSmjGoodListByMachineId(tSmjMachineList.getId());
            }
            logger.info("后台货品HTMLurl：" + loginUrls[0] + "operator/huodao.html?id=" + tSmjMachineList.getSmMachineId());
            HttpResponse adhttpResponse = HttpUtils.httpFormGet(loginUrls[0] + "operator/huodao.html?id=" + tSmjMachineList.getSmMachineId(), headerMap, "", "售货机", "");
            if (adhttpResponse.getBody().contains("登录")) {
                adhttpResponse = reGetUrl(tUserRecipientInfo, loginUrls[0] + "operator/huodao.html?id=" + tSmjMachineList.getSmMachineId(),dataMap);
            }
            Document addocument = adhttpResponse.getDocument();
            Element divele = addocument.getElementById("content");
            Elements tbody = divele.select("tbody");
            Elements trs = tbody.first().select("tr");
            JSONObject trObj = new JSONObject();
            for (int i = 0; i < trs.size(); i++) {
                Element tr = trs.get(i);
                Elements cells = tr.select("td");
                Element checkboxe = cells.get(0).select("input[type=checkbox]").first();
                trObj.put(cells.get(1).text(), checkboxe.val() + "#" + cells.get(5).text());
                TSmjGoodList tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
//            tSmjGoodList.setRealChannelCode(tSmjMachineList.getRealChannelCode());
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                String hd = cells.get(1).text();
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("ALI");
                tSmjGoodList.setRealChannelCode("alipay_smj_sm_h5");
                List<TSmjGoodList> tSmjGoodLists = tSmjGoodListMapper.selectTSmjGoodListList(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());

                //获取商品链接
                String href = spObj.getString(hd);
                if (StringUtils.isBlank(href)) {
                    tSmjGoodList.setGoodStatus(1);
                    tSmjGoodListMapper.updateTSmjGoodList(tSmjGoodList);
                    continue;
                }
                tSmjGoodList.setGoodUrl(href.replace("payInfo.html","payInfo_alipay.html"));
                String goodName = cells.get(3).text();
                tSmjGoodList.setGoodName(goodName);
                tSmjGoodList.setSmGoodId(trObj.getString(hd).split("#")[0]);
                tSmjGoodList.setGoodNum(Long.valueOf(trObj.getString(hd).split("#")[1]));
                String price = cells.get(6).text();
                tSmjGoodList.setGoodPrice(new BigDecimal(price.replace("￥", "")).setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    tSmjGoodListMapper.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    tSmjGoodListMapper.insertTSmjGoodList(tSmjGoodList);
                }
                tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                tSmjGoodList.setRealChannelCode("wechat_smj_sm_h5");
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("WX");
                tSmjGoodLists = tSmjGoodListMapper.selectTSmjGoodListList(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());
                tSmjGoodList.setGoodUrl(href);
                tSmjGoodList.setGoodName(goodName);
                tSmjGoodList.setSmGoodId(trObj.getString(hd).split("#")[0]);
                tSmjGoodList.setGoodNum(Long.valueOf(trObj.getString(hd).split("#")[1]));
                tSmjGoodList.setGoodPrice(new BigDecimal(price.replace("￥", "")).setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    tSmjGoodListMapper.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    tSmjGoodListMapper.insertTSmjGoodList(tSmjGoodList);
                }
            }
            //刪除redis緩存
            redisUtil.removePattern("PLATFORM_SMJSMALI*");
            redisUtil.removePattern("PLATFORM_SMJSMWX*");
        }else if (tUserRecipientInfo.getChannel().contains("_smj_xlm_h5")) {
            headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            headerMap.put("Cookie", accountObj.getString("cookie"));
            dataMap.put("saleLocId",tSmjMachineList.getSmMachineId());
            HttpResponse httpResponse =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18",headerMap,accountObj.getString("cookie"),dataMap,"售货机【小懒猫】","");
            logger.info("获取商品信息返回：{}",JSONObject.toJSONString(httpResponse));
            if(!httpResponse.getIsSuccess()){
                httpResponse = reGetUrl(tUserRecipientInfo,"https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18",dataMap);
            }
            JSONObject jsonObject = JSONObject.parseObject(httpResponse.getBody());
            JSONArray rackDetails =jsonObject.getJSONArray("rackDetails");
            for(int i=0;i<rackDetails.size();i++){
                JSONObject rackDetail = rackDetails.getJSONObject(i);
                TSmjGoodList tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
//            tSmjGoodList.setRealChannelCode(tSmjMachineList.getRealChannelCode());
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                String hd = rackDetail.getString("rackNo");
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("ALI");
                tSmjGoodList.setRealChannelCode("alipay_smj_xlm_h5");
                List<TSmjGoodList> tSmjGoodLists = tSmjGoodListMapper.selectTSmjGoodListList(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());

                //获取商品链接
                tSmjGoodList.setGoodUrl(rackDetail.getString("visionImageUrl"));

                tSmjGoodList.setGoodName(rackDetail.getString("goodsName"));
                tSmjGoodList.setSmGoodId(rackDetail.getString("goodId"));
                tSmjGoodList.setGoodNum(rackDetail.getLongValue("goodNum"));
                tSmjGoodList.setGoodPrice(rackDetail.getBigDecimal("noncashPrice").setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    tSmjGoodListMapper.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    tSmjGoodListMapper.insertTSmjGoodList(tSmjGoodList);
                }
                tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("WX");
                tSmjGoodList.setRealChannelCode("wechat_smj_xlm_h5");
                tSmjGoodLists = tSmjGoodListMapper.selectTSmjGoodListList(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());
                tSmjGoodList.setGoodUrl(rackDetail.getString("visionImageUrl"));

                tSmjGoodList.setGoodName(rackDetail.getString("goodsName"));
                tSmjGoodList.setSmGoodId(rackDetail.getString("goodId"));
                tSmjGoodList.setGoodNum(rackDetail.getLongValue("goodNum"));
                tSmjGoodList.setGoodPrice(rackDetail.getBigDecimal("noncashPrice").setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    tSmjGoodListMapper.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    tSmjGoodListMapper.insertTSmjGoodList(tSmjGoodList);
                }
                //刪除redis緩存
//                redisUtil.remove("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
//                redisUtil.remove("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
            }
            redisUtil.removePattern("PLATFORM_SMJXLMALI*");
            redisUtil.removePattern("PLATFORM_SMJXLMWX*");
        }
        tSmjMachineList.setUpdateTime(DateUtils.getNowDate());
        return AjaxResult.success(tSmjMachineListMapper.updateTSmjMachineList(tSmjMachineList));
    }

    private HttpResponse reGetUrl(TRecipientInfo tUserRecipientInfo,String goodUrl,HashMap<String, String>  dataMap){
        HttpResponse httpResponse = null;
        String accountJson = tUserRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        logger.info("后台登录HTMLurl："+accountObj.getString("loginUrl"));
        if (tUserRecipientInfo.getChannel().contains("_smj_sm_h5")) {
            HttpResponse loginResponse = HttpUtils.httpFormGet(accountObj.getString("loginUrl"), headerMap, "", "售货机【盛马】", "");
            String cookies = loginResponse.getCookie();
            headerMap.put("Cookie", cookies);
            logger.info("登录cookies：{}", cookies);
            accountObj.put("cookie", cookies);
            accountObj.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            HashMap<String, String> requestMap = new HashMap();
            requestMap.put("username", tUserRecipientInfo.getChannelAccount());
            requestMap.put("password", accountObj.getString("password"));
            String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
            logger.info("登录地址：{},用户名：{},password:{}", loginUrls[0] + "user/login.action", tUserRecipientInfo.getChannelAccount(), accountObj.getString("password"));
            HttpResponse b = HttpUtils.httpFormPost(loginUrls[0] + "user/login.action", headerMap, cookies, requestMap, "售货机【盛马】", "");
            accountObj.put("cookie", cookies);
            tUserRecipientInfo.setAccountJson(accountObj.toJSONString());
            tUserRecipientInfoMapper.updateTRecipientInfo(tUserRecipientInfo);
            headerMap.put("Cookie", b.getCookie());
            httpResponse = HttpUtils.httpFormGet(goodUrl, headerMap, "", "售货机", "");
        }else if (tUserRecipientInfo.getChannel().contains("_smj_xlm_h5")) {
            headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            logger.info("后台登录HTMLurl："+accountObj.getString("loginUrl"));
            HttpResponse loginResponse  = HttpUtils.httpFormGet(accountObj.getString("loginUrl"),headerMap,"","售货机【小懒猫】","");
            String cookies = loginResponse.getCookie();
            headerMap.put("Cookie",cookies);
            logger.info("登录cookies：{}",cookies);
            accountObj.put("cookie",cookies);
            accountObj.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            HashMap<String, String> requestMap = new HashMap();
            requestMap.put("userCode",tUserRecipientInfo.getChannelAccount());
            requestMap.put("password",accountObj.getString("password"));
            logger.info("登录地址：{},用户名：{},password:{}","https://xxh.aotaki.com/api/h5b/login",tUserRecipientInfo.getChannelAccount(),accountObj.getString("password"));
            loginResponse =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/h5b/login",headerMap,cookies,requestMap,"售货机【小懒猫】","");
            logger.info("登录返回：{}",JSONObject.toJSONString(loginResponse));
            cookies = cookies+";"+loginResponse.getCookie();
            accountObj.put("cookie",cookies);
            headerMap.put("Cookie",cookies);
            String userStr = loginResponse.getBody();
            JSONObject userObj = JSONObject.parseObject(userStr);
            if(!userObj.getBooleanValue("success")){
                return null;
            }
            httpResponse =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18",headerMap,accountObj.getString("cookie"),dataMap,"售货机【小懒猫】","");
            logger.info("查商品返回：{}",JSONObject.toJSONString(httpResponse));
            accountObj.put("deptId",userObj.getJSONObject("user").getString("deptId"));
            tUserRecipientInfo.setAccountJson(accountObj.toJSONString());
            tUserRecipientInfoMapper.updateTRecipientInfo(tUserRecipientInfo);
        }
        return httpResponse;
    }

    /**
     * 解析二维码
     */
    private String  decodeQR(String filePath) {
//        String filePath = "E:/txdata/data/images/qrCode.jpg";//二维码路径
        BufferedImage image;
        Result result = null;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            logger.info("图片中内容：  ");
            logger.info("author： " + result.getText());
            logger.info("图片中格式：  ");
            logger.info("encode： " + result.getBarcodeFormat());
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
